package cn.jobstart.common;

import org.fit.cssbox.demo.ImageRenderer;
import org.xml.sax.SAXException;

import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * @author sunke
 * @Date 2021/4/15 01:40
 * @description
 */

public class HtmlToImageUtil {


    public static void main(String[] args) throws Exception {
        try {
            ImageRenderer render = new ImageRenderer();
            render.setWindowSize(new Dimension(800, 800), false);
            FileOutputStream out = new FileOutputStream(new File("/Users/sunke/Desktop/aa/cssbox.png"));
            String url = "file:///Users/sunke/Desktop/aa/a.html";

            render.renderURL(url, out, ImageRenderer.Type.PNG);
            System.out.println("end.");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public static void html2Img(int w, int h, String content, String fieDir, String filePath) {


        try {

            if (!FileUtil.exists(fieDir)) {
                FileUtil.mkdirs(fieDir);
            }



            String targetFilePath=fieDir+File.separator+filePath;


            String tmpHtmlFile=fieDir+File.separator+YXDate.getFormatDate2String(new Date(),"yyyyMMddHHmmss")+".html";

            ImageRenderer render = new ImageRenderer();
            render.setWindowSize(new Dimension(w, h), true);
            FileOutputStream out = new FileOutputStream(new File(targetFilePath));

            StringBuffer html=new StringBuffer("<!DOCTYPE html>" +
                    "<html lang=\"en\">" +
                    "<head>\n" +
                    "    <meta charset=\"UTF-8\"></meta>\n" +
                    "    <title></title>" +
                    "    <style>" +
                    "        *{margin: 0 auto;}" +
                    "    </style>" +
                    "</head>" +
                    "<body>");

            html.append(content);

            html.append("</body></html>");


            FileUtil.writeInFile(tmpHtmlFile,html.toString(),false);



            String url = "file://"+tmpHtmlFile;

            render.renderURL(url, out, ImageRenderer.Type.PNG);

            FileUtil.deleteFile(tmpHtmlFile);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }


    }

}
